//
//  FractionTopic.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/8/1.
//
//  分数 -> 小数

import UIKit

class FractionTopic: BaseTopic {
    
    /// 分子
    var numerator: Float = 0
    /// 分母
    var denominator: Float = 1
    
    var answer: Float = 0.0
    var inputAnswer: Float?
    
    init(numerator: Float, denominator: Float) {
        self.numerator = numerator
        self.denominator = denominator
        self.answer = numerator / denominator
    }
    
    override func setInputAnswer(answer: String?, numerator: Float = 0.0, denominator: Float = 1) {
        self.inputAnswer = Float(answer ?? "0.0") ?? 0.0
    }
    
    override func getTopicDesc() -> String {
        return "\\frac{\(Int(numerator))}{\(Int(denominator))} = \\; ?\\%"
    }
    
    override func answerIsCorrect() -> Bool {
        let minAnswer = answer - 0.001
        let maxAnswer = answer + 0.001
        
        guard var tAnswer = inputAnswer else { return false }
        
        tAnswer = tAnswer * 0.01
        if tAnswer > minAnswer && tAnswer < maxAnswer {
            return true
        }
        
        return false
    }
    
    override func getResultDesc() -> NSMutableAttributedString {
        var sym = "√"
        var color = UIColor.black
        if !answerIsCorrect() {
            sym = "×"
            color = .red
        }
        
        let answerStr = String(format: "%.3f", answer)
        let tInputAnswer = (inputAnswer ?? 0.0) * 0.01
        let inputAnswerStr = String(format: "%.3f", tInputAnswer)
        let desc = "\(Int(numerator)) / \(Int(denominator)) = \(answerStr) (\(inputAnswerStr)) \(sym)"
        
        let attri = NSMutableAttributedString(string: desc)
        let tmpRange = NSRange(location: desc.count - 1, length: 1)
        
        attri.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: tmpRange)
        return attri
    }
}
